<?php

namespace App\Listeners;

use App\Common\Constant\Params;
use App\Events\MasterOffer;
use App\Events\MasterPunished;
use App\Events\OrderOffered;
use App\Models\MerchantOrderNum;
use App\Models\Order;
use App\Models\OrderComplain;
use App\Notifications\OrderNotifications\OrderOfferedNotification;
use App\Services\IMasterLogService;
use App\Services\IWalletService;
use DB;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class OrderOfferedListener implements ShouldQueue
{

    use InteractsWithQueue;

    public $queue = 'order';

    public $tries = 3;

    public $timeout = 30;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @return void
     */
    public function handle(OrderOffered $event)
    {
        $order = Order::find($event->order_id);
        if(!$order){
            throw new \Exception('miss order');
        }

        $ret = MerchantOrderNum::where([
            'me_id'=>$order->merchant_id,
            'order_type'=>Params::ORDER_TYPE_OFFER
        ])->take(1)->update([
            'wait_hired'=>DB::raw('wait_hired+1'),
            'wait_priced'=>DB::raw('IF(wait_priced>0,wait_priced-1,wait_priced)'),
        ]);
        if(!$ret){
            throw new \Exception('merchant order num update fail');
        }

        $order->merchant->notify(new OrderOfferedNotification($order));
    }

    public function failed(OrderOffered $event, \Exception $exception)
    {
        //
    }
}
